package com.example.starter.security.handler;

import com.example.starter.security.constant.SecurityExceptionEnum;
import com.example.starter.util.ResponseEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>
 * 统一异常处理
 * </p>
 *
 * @author 王令
 * @since 2022-05-13 15:14:14
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
@RestControllerAdvice
public class SecurityExceptionHandler {

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseEntity<String> usernameNotFound(Exception e) {
        return ResponseEntity.fail("用户不存在");
    }

    @ExceptionHandler(InvalidGrantException.class)
    public ResponseEntity<String> invalidGrant(Exception e) {
        return ResponseEntity.fail(e.getLocalizedMessage());
    }

    @ExceptionHandler(InvalidTokenException.class)
    public ResponseEntity<String> invalidToken(Exception e) {
        return ResponseEntity.fail(e.getLocalizedMessage());
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<String> accessDenied(Exception e) {
        return ResponseEntity.fail(SecurityExceptionEnum.ACCESS_DENIED);
    }

    @ExceptionHandler
    public ResponseEntity<String> badCredentialsException(BadCredentialsException e) {
        return ResponseEntity.fail(SecurityExceptionEnum.INVALID_GRANT);
    }

    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public ResponseEntity<String> internalAuthenticationServiceError(Exception e) {
        return ResponseEntity.error(SecurityExceptionEnum.INTERNAL_AUTHENTICATION_ERROR);
    }

}
